package com.hu.service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledFuture;

/**
 * @author 00355760
 * @功能：
 * @版本： V1
 * @版权： 信息技术有限公司（http://www.mychery.com/）
 * @作者： 磐石战队开发组  00355760
 * @日期： 2024/12/19 19:34
 */
@Service
@Slf4j
public class MyThreadService4 {

    private static final Logger logger = LoggerFactory.getLogger(MyThreadService4.class);
    private final ThreadPoolTaskScheduler scheduler;
    private ScheduledFuture<?> scheduledFuture;

    public MyThreadService4(ThreadPoolTaskScheduler scheduler) {
        this.scheduler = scheduler;
    }

    @PostConstruct
    public void init() {
        scheduledFuture = scheduler.scheduleWithFixedDelay(() -> {
            try {
                logger.info("异步开始！");
            } catch (Exception e) {
                logger.error("异步任务执行失败", e);
            }
        }, 1000);
    }

    @PreDestroy
    public void destroy() {
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(true);
        }
    }

    public void executeAsyncTask(CountDownLatch latch) {
        scheduler.execute(() -> {
            try {
                logger.info("异步任务执行 - 线程: {}", Thread.currentThread().getName());
            } catch (Exception e) {
                logger.error("异步任务执行失败", e);
            } finally {
                latch.countDown();
            }
        });
    }
}
